﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Shared
{
    class AES
    {

        private static RijndaelManaged CreateRijndaelManagedWithKey(string key)
        {
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key.PadRight(16, '\0')),
                Mode = CipherMode.CBC,
                Padding = PaddingMode.Zeros,
                IV = new byte[16] { 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30 },
            };
            return rm;
        }
        public static String AESEncrypt(String key, String str)
        {            
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str ?? "");
            ICryptoTransform cTransform = CreateRijndaelManagedWithKey(key).CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);            
            return ToBCDEncode(resultArray);
        }

        public static String AESDecrypt(String key, String str)
        {            
            Byte[] toEncryptArray = ToBCDDecode(str ?? "");
            ICryptoTransform cTransform = CreateRijndaelManagedWithKey(key).CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray).TrimEnd('\0');
        }


        private static String ToBCDEncode(byte[] input)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte b in input)
            {
                string hexOutput = String.Format("{0:X2}", (int)b);
                sb.Append(hexOutput);
            }
            return sb.ToString();
        }

        private static byte[] ToBCDDecode(String input)
        {
            byte[] output = new byte[input.Length / 2];
            for (int i = 0; i < input.Length / 2; i++)
            {
                int hex = Convert.ToInt32(input.Substring(i * 2, 2), 16);
                output[i] = (byte)hex;
            }
            return output;
        }
    }
}
